package chat.server;

import java.net.Socket;
import java.util.*;
import chat.user.*;

public class GroupProcessor {

	private static Vector<Group> group_list_new = new Vector<Group>();

	private static Set<Socket> socket_list = new HashSet<Socket>();
	private static Group general = new Group ("General");
	// private static ArrayList<User> user_list = new ArrayList<User>();

	public GroupProcessor() {

		//group_list_new.add(root);
		group_list_new.add(general);
	}

	public static boolean addToGroupList(String group_name) {

		Group new_group = new Group(group_name);

		return group_list_new.add(new_group);

	}

	public static Vector<Group> getGroupList() {

		return group_list_new;
	}

	/*public static Group getRoot() {
		return root;
	}
	*/
	public static Group getGroup(String g) {

		Group group = null;

		for (Group gr : group_list_new) {

			if (gr.getName().equals(g)) {

				return group = gr;
			}

		}

		return group;
	}

	public static void addUserToGroup(User u, Group group) {

		for (Group g : group_list_new) {

			if (g.equals(group)) {

				g.addUser(u);

				u.updateRelatedGroup(g.getName());

			}
		}
	}

	public static void registerNewUser(Socket socket, User user) {

		user.setSocketID(socket.hashCode());
		
		GroupProcessor.addUserSocket(socket);
		
		general.addUser(user);

		user.updateRelatedGroup(general.getName());
	}

	public static void connectToGroup(String toGroup, String username) {

		boolean flag = false;

		for (Group g : group_list_new) {

			if (!flag) {

				for (User u : g.getUserList()) {

					if (u.getUserName().equalsIgnoreCase(username)) {

						g.removeUser(u);
						
						getGroup(toGroup).addUser(u);

						flag = true;

						break;
					}
				}
			}
		}

	}
	
	public static void addUserSocket(Socket socket){
		socket_list.add(socket);
	}
	
	public static Socket getSocket(User user){
		
		Socket socket = null;
		
		for (Socket s: socket_list){
			if (s.hashCode() == user.getSocketID()){
				socket = s;
			}
		}
		
		return socket;
	}
}
